package com.ivr.cm.chain.dispatcher;

import java.net.URLEncoder;
import java.util.AbstractMap;
import java.util.HashMap;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.log4j.Logger;

import com.ivr.cm.cache.impl.ConfigRouterCache;
import com.ivr.cm.chain.ServiceIF;
import com.ivr.cm.dao.IDispatcherReadyDao;
import com.ivr.cm.send.Sender;
import com.ivr.cm.service.impl.DbService;
import com.ivr.cm.util.SpringServiceUtil;
import com.ivr.cm.vo.ConfigRouterVo;
import com.ivr.cm.vo.DispatcherReadyVo;
import com.ivr.cm.vo.DispatcherResultVo;
import com.ivr.cm.vo.UserBillVo;

public class DispatchService implements ServiceIF<UserBillVo> {
	private static Logger logger = Logger.getLogger(DispatchService.class);
	
	private Sender httpSender;
	private IDispatcherReadyDao dispatcherReadyDao;
	private SpringServiceUtil serviceLocator;

	public boolean doProcess(UserBillVo userBillVo) {
		HashMap<String, Object> hm = new HashMap<String, Object>();
		ConfigRouterCache configRouterCache = (ConfigRouterCache) SpringServiceUtil.getService("configRouterCache");
		AbstractMap<String, ConfigRouterVo> configRouterMap = (AbstractMap<String, ConfigRouterVo>) configRouterCache.getCache();
		ConfigRouterVo configRouterVo = configRouterMap.get(userBillVo.getSp_number());
		if(configRouterVo != null){
			/**根据长号码获得URL地址*/
			String sync_url = configRouterVo.getSync_url();
			/**获得参数*/
			String method = getMethod(userBillVo);
			hm.put("url", sync_url+"?"+method);
			hm.put("method", "get");
			logger.info(String.format("[%s][%s][HTTP转发]URL[%s]", userBillVo.getMobile(),userBillVo.getSp_number(),sync_url+"?"+method));
			long start_time = System.currentTimeMillis();
			
			try {
				Integer result = (Integer) httpSender.sendObject(hm);
				logger.info(String.format("[%s][%s][HTTP转发]HTTP发送完成,返回["+result+"],耗时["+(System.currentTimeMillis() - start_time)+"]ms", userBillVo.getMobile(),userBillVo.getSp_number()));
				
				/**同步成功*/
				if(result == HttpStatus.SC_OK){
					/**入成功库*/
					DispatcherResultVo dispatcherResultVo = new DispatcherResultVo();
					dispatcherResultVo.setMobile(userBillVo.getMobile());
					dispatcherResultVo.setLinkId(userBillVo.getLinkId());
					dispatcherResultVo.setSync_url(sync_url);
					dispatcherResultVo.setParameter(method);
					dispatcherResultVo.setType("get");
					dispatcherResultVo.setStatus_code(HttpStatus.SC_OK);
					dispatcherResultVo.setLower_id(userBillVo.getLower_id());
					dispatcherResultVo.setRouter_id(userBillVo.getRouter_id());
					dispatcherResultVo.setDis_count(1);
					DbService dbService = (DbService) SpringServiceUtil.getService("dbService");
					dbService.doProcess(dispatcherResultVo);
					
					dispatcherReadyDao.deleteDispatcherReadyByLinkId(userBillVo.getLinkId());
					logger.info(String.format("[%s][%s][HTTP转发]保存转发数据成功!", userBillVo.getMobile(),userBillVo.getSp_number()));
				}else{
					updateDispatcherReady(userBillVo,result);
					logger.info(String.format("[%s][%s][HTTP转发]保存预转发数据成功!", userBillVo.getMobile(),userBillVo.getSp_number()));
				}
			} catch (Throwable e) {
				logger.error(String.format("[%s][%s][HTTP转发]HTTP发送失败!%s", userBillVo.getMobile(),userBillVo.getSp_number(),e.getMessage()));
				updateDispatcherReady(userBillVo, 504);
				logger.info(String.format("[%s][%s][HTTP转发]保存预转发数据成功!", userBillVo.getMobile(),userBillVo.getSp_number()));
			}
		}else{
			logger.info(String.format("[%s][%s][HTTP转发]长号码未匹配到路由信息!", userBillVo.getMobile(),userBillVo.getSp_number()));
			updateDispatcherReady(userBillVo,419);
			logger.info(String.format("[%s][%s][HTTP转发]保存预转发数据成功!", userBillVo.getMobile(),userBillVo.getSp_number()));
		}
		return true;
	}
	
	private void updateDispatcherReady(UserBillVo userBillVo, int status_code){
		/**根据linkId查询表是否存在  存在+1 不存在 新增*/
		int dis_count = dispatcherReadyDao.getDispatcherReadyByLinkId(userBillVo.getLinkId());
		if(dis_count == 0){
			/**入预备库*/
			DispatcherReadyVo dispatcherReadyVo = new DispatcherReadyVo();
			dispatcherReadyVo.setMobile(userBillVo.getMobile());
			dispatcherReadyVo.setSp_number(userBillVo.getSp_number());
			dispatcherReadyVo.setStart_time(userBillVo.getTime_begin());
			dispatcherReadyVo.setEnd_time(userBillVo.getTime_end());
			dispatcherReadyVo.setSecond(userBillVo.getSecond());
			dispatcherReadyVo.setMinute(userBillVo.getMinute());
			dispatcherReadyVo.setLinkId(userBillVo.getLinkId());
			dispatcherReadyVo.setLower_id(userBillVo.getLower_id());
			dispatcherReadyVo.setRouter_id(userBillVo.getRouter_id());
			dispatcherReadyVo.setStatus_code(status_code);
			dispatcherReadyVo.setDis_count(1);
			
			DbService dbService = (DbService) SpringServiceUtil.getService("dbService");
			dbService.doProcess(dispatcherReadyVo);
		}else{
			/**根据linkId更新转发数量*/
			dispatcherReadyDao.updateDispatcherReadyDisCountByLinkId(userBillVo.getLinkId(), (dis_count + 1), status_code);
		}
	}
	
	
	private String getMethod(UserBillVo userBillVo){
		StringBuffer method = new StringBuffer();
		try {
			method.append("mobile=" + userBillVo.getMobile());
			method.append("&longnumber=" + userBillVo.getSp_number());
			method.append("&linkid=" + userBillVo.getLinkId());
			method.append("&minute=" + userBillVo.getMinute());
			method.append("&stime=" + URLEncoder.encode(userBillVo.getTime_begin(), "GBK"));
			method.append("&etime=" + URLEncoder.encode(userBillVo.getTime_end(), "GBK"));
			
			return method.toString();
		} catch (Exception e) {
			logger.info(String.format("[%s][%s][HTTP转发]参数处理异常%s", userBillVo.getMobile(),userBillVo.getSp_number(),e.getMessage()));
		}
		return "";
	}

	public Sender getHttpSender() {
		return httpSender;
	}
	public void setHttpSender(Sender httpSender) {
		this.httpSender = httpSender;
	}
	public IDispatcherReadyDao getDispatcherReadyDao() {
		return dispatcherReadyDao;
	}
	public void setDispatcherReadyDao(IDispatcherReadyDao dispatcherReadyDao) {
		this.dispatcherReadyDao = dispatcherReadyDao;
	}
	public SpringServiceUtil getServiceLocator() {
		return serviceLocator;
	}
	public void setServiceLocator(SpringServiceUtil serviceLocator) {
		this.serviceLocator = serviceLocator;
	}
}
